#include "../decoder_conf.h"

#if DECODER_FS == DECODER_FS_FATFS
#include "../decoder_fs.h"

#include "ff.h"

void *DecoderFs::openFile(const char *path)
{
    FIL *file = new FIL;

    FRESULT res = f_open(file, path, FA_READ);
    if (res != FR_OK)
    {
        delete file;
        return nullptr;
    }

    return file;
}

void DecoderFs::closeFile(void *file)
{
    f_close((FIL *)file);
    delete (FIL *)file;
}

void DecoderFs::seekFile(void *file, int pos, Whence whence)
{
    switch (whence)
    {
    case SeekSet:
        f_lseek((FIL *)file, pos);
        break;
    case SeekCur:
        f_lseek((FIL *)file, f_tell((FIL *)file) + pos);
        break;
    case SeekEnd:
        f_lseek((FIL *)file, f_size((FIL *)file) + pos);
        break;
    default:
        break;
    }
}

size_t DecoderFs::readFile(void *file, uint8_t *buf, size_t cnt)
{
    uint32_t br = 0;

    FRESULT res = f_read((FIL *)file, buf, cnt, (UINT *)&br);
    if (res != FR_OK)
        return 0;

    return br;
}

size_t DecoderFs::sizeofFile(void *file)
{
    return f_size((FIL *)file);
}

#endif
